<template>
  <div class="weather-set">
    <div class="weather-form">
      <el-form :model="weatherForm" label-width="100px" size="default">
        <!-- 阳光设置 -->
        <div class="weather-group">
          <el-divider content-position="left">
            <div class="divider-content">
              <span>sunlight</span>
              <el-button
                class="preview-btn"
                type="primary"
                link
                @click="handlePreview('sunlight')"
                :loading="loading.sun"
              >
                <el-icon><View /></el-icon>
                preview
              </el-button>
              <el-button
                  class="preview-btn"
                  type="primary"
                  link
                  @click="handleSet('sunlight')"
              >
                <el-icon><Setting /></el-icon>
                set
              </el-button>
            </div>
          </el-divider>
          <el-form-item label="color">
            <el-color-picker
              v-model="sunlightColor"
              :show-alpha="true"
              @change="handleSunlightColorChange"
            />
          </el-form-item>
          <el-form-item label="Brightness">
            <el-input-number
              v-model="weatherForm.sunlight.brightness"
              :min="0"
              :max="10"
              :step="0.1"
              :precision="1"
            />
          </el-form-item>
        </div>

        <!-- 雾设置 -->
        <div class="weather-group">
          <el-divider content-position="left">
            <div class="divider-content">
              <span>fog</span>
              <el-button
                class="preview-btn"
                type="primary"
                link
                @click="handlePreview('fog')"
                :loading="loading.fog"
              >
                <el-icon><View /></el-icon>
                preview
              </el-button>
              <el-button
                  class="preview-btn"
                  type="primary"
                  link
                  @click="handleSet('fog')"
              >
                <el-icon><Setting /></el-icon>
                set
              </el-button>
            </div>
          </el-divider>
          <el-form-item label="color">
            <el-color-picker
              v-model="fogColor"
              :show-alpha="true"
              @change="handleFogColorChange"
            />
          </el-form-item>
          <el-form-item label="Density">
            <el-input-number
              v-model="weatherForm.fog.density"
              :min="0"
              :max="10"
              :step="0.1"
              :precision="1"
            />
          </el-form-item>
          <el-form-item label="Height">
            <el-input-number
              v-model="weatherForm.fog.height"
              :min="-1000"
              :max="1000"
              :step="100"
            />
          </el-form-item>
          <el-form-item label="Height Attenuation">
            <el-input-number
              v-model="weatherForm.fog.heightAttenuation"
              :min="0"
              :max="1"
              :step="0.1"
              :precision="1"
            />
          </el-form-item>
          <el-form-item label="Start Distance">
            <el-input-number
              v-model="weatherForm.fog.startDistance"
              :min="0"
              :max="300"
              :step="10"
              :precision="1"
            />
          </el-form-item>
        </div>

        <!-- 雪设置 -->
        <div class="weather-group">
          <el-divider content-position="left">
            <div class="divider-content">
              <span>snow</span>
              <el-button
                class="preview-btn"
                type="primary"
                link
                @click="handlePreview('snow')"
                :loading="loading.snow"
              >
                <el-icon><View /></el-icon>
                preview
              </el-button>
              <el-button
                  class="preview-btn"
                  type="primary"
                  link
                  @click="handleSet('snow')"
              >
                <el-icon><Setting /></el-icon>
                set
              </el-button>
            </div>
          </el-divider>
          <el-form-item label="Height">
            <el-input-number
              v-model="weatherForm.snow.height"
              :min="0"
              :max="10000"
              :step="1000"
              :precision="1"
            />
          </el-form-item>
          <el-form-item label="Speed">
            <el-input-number
              v-model="weatherForm.snow.speed"
              :min="0"
              :max="500"
              :step="1"
            />
          </el-form-item>
          <el-form-item label="Time Scale">
            <el-input-number
              v-model="weatherForm.snow.timeScale"
              :min="0"
              :max="10"
              :step="1"
              :precision="1"
            />
          </el-form-item>
          <el-form-item label="Snow Size Multiplier">
            <div class="size-inputs">
              <el-input-number style="width: 140px"
                v-model="weatherForm.snow.size[0]"
                :min="0"
                :max="100"
                :step="1"
                :precision="1"
              />
              <span class="separator">-</span>
              <el-input-number style="width: 140px"
                v-model="weatherForm.snow.size[1]"
                :min="0"
                :max="30000"
                :step="1"
                :precision="1"
              />
            </div>
          </el-form-item>
          <el-form-item label="Density">
            <el-input-number
              v-model="weatherForm.snow.density"
              :min="0"
              :step="100"
            />
          </el-form-item>
          <el-form-item label="Shape">
            <el-select v-model="weatherForm.snow.shape.selected">
              <el-option
                v-for="shape in weatherForm.snow.shape.available"
                :key="shape"
                :label="shape"
                :value="shape"
              />
            </el-select>
          </el-form-item>
        </div>
      </el-form>
    </div>

    <div class="weather-preview" ref="previewEl" :style="backgroundStyle">
      <!-- 预览区域 -->
    </div>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted, computed, onBeforeUnmount} from 'vue'
import {weatherInit, previewWeather, getMap, weatherFog, weatherSnow, weatherSunlight} from '../api'
import { ElMessage } from 'element-plus'
import { View, Setting } from '@element-plus/icons-vue'

// 修改 loading 状态为对象，分别控制每个预览按钮的状态
const loading = reactive({
  sun: false,
  fog: false,
  snow: false
})

const backgroundStyle = ref({})

// 天气设置表单数据
const weatherForm = reactive({
  sunlight: {
    color: [1.0, 1.0, 1.0, 1.0],
    brightness: 1
  },
  fog: {
    color: [0.25, 0.25, 0.26, 1.0],
    density: 0.06,
    height: 0,
    heightAttenuation: 0.39,
    startDistance: 845
  },
  snow: {
    height: 4160,
    speed: 150,
    timeScale: 1.0,
    size: [5, 12],
    density: 15000,
    shape: {
      available: ["flake", "crystal", "powder"],
      selected: "flake"
    }
  }
})

// 获取初始数据
function fetchInitialData() {
  getBackgroundImage()
  getWeatherSettings()
}

// 获取背景图片
function getBackgroundImage() {
  console.log('获取背景图片')
  getMap({

  }).then(res => {
    if (res.success) {
      backgroundStyle.value = {
        backgroundImage: `url(${res.image})`,
        backgroundSize: 'cover',
        backgroundPosition: 'center',
        backgroundRepeat: 'no-repeat'
      }
    }
  })
}

// 获取背景图片
function getWeatherSettings() {
  weatherInit({

  }).then(res => {
    Object.assign(weatherForm, res.data)
  })
}

// 修改预览函数，接收天气类型参数
function handlePreview(category) {
  loading[category] = true
  previewWeather({
    category: category
  }).then(res => {
    loading[category] = false
    if (!res.success) {
      ElMessage.error(res.message || 'preview fail')
    }
  })
}

// 设置天气参数
function handleSet(category) {
  const api = category === 'sunlight' ? weatherSunlight : category === 'fog' ? weatherFog : weatherSnow
  api(weatherForm[category]).then(res => {
    if (res.success) {
      ElMessage.success(res.message || 'set success')
    } else {
      ElMessage.error(res.message || 'set fail')
    }
  })
}

// 将 RGBA 数组转换为十六进制颜色值
const rgbaToHex = (rgba) => {
  const r = Math.round(rgba[0] * 255)
  const g = Math.round(rgba[1] * 255)
  const b = Math.round(rgba[2] * 255)
  const a = rgba[3]
  return `rgba(${r}, ${g}, ${b}, ${a})`
}

// 将十六进制颜色值转换为 RGBA 数组
const hexToRgba = (hex) => {
  // 从 rgba(r, g, b, a) 格式解析颜色值
  const rgba = hex.match(/[\d.]+/g)
  return [
    Number((Number(rgba[0]) / 255).toFixed(2)),
    Number((Number(rgba[1]) / 255).toFixed(2)),
    Number((Number(rgba[2]) / 255).toFixed(2)),
    Number(rgba[3])
  ]
}

// 阳光颜色的计算属性
const sunlightColor = computed({
  get: () => rgbaToHex(weatherForm.sunlight.color),
  set: (value) => {
    weatherForm.sunlight.color = hexToRgba(value)
  }
})

// 雾颜色的计算属性
const fogColor = computed({
  get: () => rgbaToHex(weatherForm.fog.color),
  set: (value) => {
    weatherForm.fog.color = hexToRgba(value)
  }
})

// 处理阳光颜色变化
const handleSunlightColorChange = (value) => {
  if (value) {
    weatherForm.sunlight.color = hexToRgba(value)
  }
}

// 处理雾颜色变化
const handleFogColorChange = (value) => {
  if (value) {
    weatherForm.fog.color = hexToRgba(value)
  }
}

onMounted(() => {
  window.addEventListener('resize', resizePreview)
  resizePreview()
  fetchInitialData()
})

const previewEl = ref(null)

function resizePreview() {
  if (previewEl.value) {
    previewEl.value.style.width = previewEl.value.offsetHeight + 'px'
  }
}

onBeforeUnmount(() => {
  window.removeEventListener('resize', resizePreview)
})
</script>

<style scoped>
.weather-set {
  display: flex;
  height: 100%;
  gap: 20px;
  overflow: hidden;
}

.weather-form {
  width: 600px;
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  overflow-y: auto;
  overflow-x: hidden;
}

.weather-preview {
  height: 100%;
  width: 100%;
  background-color: #fff;
  border-radius: 4px;
  position: relative;
}

.color-inputs {
  display: flex;
  flex-direction: column;
  gap: 8px;
  max-height: 200px;
  overflow-y: auto;
  overflow-x: hidden;
  padding-right: 10px;
}

.color-input-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.color-label {
  width: 20px;
  text-align: right;
  color: #606266;
}

:deep(.el-input-number) {
  width: 100%;
}

:deep(.el-input-number .el-input__wrapper) {
  padding-right: 0;
}

.size-inputs {
  display: flex;
  align-items: center;
  gap: 10px;
}

.separator {
  color: #909399;
}

:deep(.el-divider__text) {
  font-size: 16px;
  font-weight: bold;
  color: #409EFF;
}

:deep(.el-color-picker__trigger) {
  width: 100%;
  height: 32px;
}

.weather-group {
  position: relative;
  width: 100%;
}

.divider-content {
  display: flex;
  align-items: center;
  gap: 8px;
  width: 100%;
}

.preview-btn {
  padding: 4px 8px;
  white-space: nowrap;
}

:deep(.el-divider__text) {
  display: flex;
  width: calc(100% - 32px);
  font-size: 16px;
  font-weight: bold;
  color: #409EFF;
  margin: 0;
  padding: 0 16px;
}

/* 调整分割线样式 */
:deep(.el-divider--horizontal) {
  margin: 16px 0;
}

/* 图标样式 */
.el-icon {
  margin-right: 4px;
}
</style>
